<?php

namespace common\helpers;

class CloudSms
{
    public $sms_url = 'https://api.rtc.huaweicloud.com:10443/sms/batchSendSms/v1';
    public $app_key;
    public $app_secret;
    public $sender;
    public $template_id;
    public $signature;
    public $statusCallback = '';
    public $template_paras = '["369751"]';

    public function sendSmsByTemplate($mobile, $content, $channel = '8819041937471', $template_id = 'f6399e4d8ba748ef856026d206c1d7c5')
    {
        $headers = [
            'Content-Type: application/x-www-form-urlencoded',
            'Authorization: WSSE realm="SDP",profile="UsernameToken",type="Appkey"',
            'X-WSSE: ' . $this->buildWsseHeader($this->app_key, $this->app_secret)
        ];
//请求Body
        $data = http_build_query([
            'from' => $channel,
            'to' => $mobile,
            'templateId' => $template_id,
            'templateParas' => $content,
            'statusCallback' => $this->statusCallback,
            'signature' => $this->signature
        ]);

        $context_options = [
            'http' => ['method' => 'POST', 'header' => $headers, 'content' => $data],
            'ssl' => ['verify_peer' => false, 'verify_peer_name' => false] //为防止因HTTPS证书认证失败造成API调用失败，需要先忽略证书信任问题
        ];

        $response = file_get_contents($this->sms_url, false, stream_context_create($context_options));
        return json_decode($response,true);
    }
    /**
     * 构造X-WSSE参数值
     * @param string $appKey
     * @param string $appSecret
     * @return string
     */
    public function buildWsseHeader(string $appKey, string $appSecret)
    {
        $now = date('Y-m-d\TH:i:s\Z'); //Created
        $nonce = uniqid(); //Nonce
        $base64 = base64_encode(hash('sha256', ($nonce . $now . $appSecret))); //PasswordDigest
        return sprintf("UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"",
            $appKey, $base64, $nonce, $now);
    }


    /**
     * 获取随机位数数字
     * @param integer $len 长度
     * @return string
     */
    public function randNumber($len = 6)
    {
        $chars = str_repeat('0123456789', 10);
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
        return $str;
    }

    public function randString($len = 6)
    {
        $chars = str_repeat('abcdefghijkmnpqrstuvwxyz', 10);
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
        return $str;
    }

    /**
     * 发送验证码
     * @param $mobile
     * @param $code
     * @return bool
     * @throws
     */
    public function verifyCode($mobile, $code)
    {
        if (\Yii::$app->redis->exists($mobile) && (\Yii::$app->redis->get($mobile) == $code)) {
            \Yii::$app->redis->del($mobile);
            return true;
        }
        return false;
    }
}